package xyz.eden.cloud.common.core.util;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.Optional;

public class DateTimeUtil {

    private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final String FORMATTER ="yyyy-MM-dd HH:mm:ss";


    private static final DateTimeFormatter DATE_FORMAT_YMD = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter FORMAT_YM = DateTimeFormatter.ofPattern("yyyyMM");


    public static LocalDateTime parseDateTime(String dateString) {
        return Optional.ofNullable(dateString).map(dt -> LocalDateTime.parse(dateString, DATE_FORMAT)).orElse(null);
    }

    public static String getUTCTime(LocalDateTime dateTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(FORMATTER);
        return formatter.withZone(ZoneOffset.UTC).format(dateTime);
    }


    public static String formatDateTime(LocalDateTime dateTime,String language) {
        ZonedDateTime zonedDateTime = ZonedDateTime.of(dateTime, ZoneId.of("GMT"));
        Locale locale = new Locale("en", "US");

        switch (language){
            case "zh-CN":
                locale = new Locale("zh", "CN");
                break;
            case "en-US":
                locale = new Locale("en", "US");
                break;
            case "ja-JP":
                locale = new Locale("ja", "JP");
                break;
            case "ko-KR":
                locale = new Locale("ko", "KR");
                break;
            default:
                locale = new Locale("en", "US");
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(FORMATTER, locale);
        return formatter.withZone(ZoneId.of("GMT")).format(zonedDateTime);
    }

    public static Long toEpochMilli(LocalDateTime dateTime) {
        return Optional.ofNullable(dateTime).map(dt -> dt.toInstant(ZoneOffset.of("+8")).toEpochMilli()).orElse(0L);
    }

    public static Long toEpochMilli(String dateString) {
        return toEpochMilli(parseDateTime(dateString));
    }

    public static String formatYMD(LocalDateTime dateTime) {
        return Optional.ofNullable(dateTime).map(d -> d.format(DATE_FORMAT_YMD)).orElse("");
    }
    public static String formatYM(LocalDateTime dateTime) {
        return Optional.ofNullable(dateTime).map(d -> FORMAT_YM.withZone(ZoneId.of("GMT")).format(d.minusHours(8))).orElse("");
    }
}
